
using System;
using System.ComponentModel;
using System.ServiceModel;
using System.Windows;
using AdventureWorks.Client.Objects;
using AdventureWorks.Services;
using Xomega.Framework;

namespace AdventureWorks.Client.WPF
{
    public partial class EmployeeDetails : Window
    {
        public static void Invoke(int kEmployeeId)
        {
            EmployeeDetails frm = new EmployeeDetails();
            frm.Load(kEmployeeId);
            frm.Show();
        }

        private EmployeeObject obj;

        public EmployeeDetails()
        {
            InitializeComponent();
        }

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            obj = new EmployeeObject();
            pnlMain.DataContext = obj;
            gridPayHistory.ItemsSource = obj.PayHistoryObjectList;
            Closing += CheckUnsavedChanges;
        }

        void CheckUnsavedChanges(object sender, CancelEventArgs e)
        {
            bool? modified = obj.IsModified();
            if (modified.HasValue && modified.Value && MessageBox.Show(
                "You have unsaved changes. Do you want to discard them and close the window?",
                "Unsaved Changes", MessageBoxButton.YesNo) == MessageBoxResult.No)
                e.Cancel = true;
        }

        private void Load(int kEmployeeId)
        {
            ChannelFactory<IEmployeeService> cfEmployee = new ChannelFactory<IEmployeeService>("IEmployeeService");
            IEmployeeService svcEmployee = cfEmployee.CreateChannel();
            obj.EmployeeIdProperty.Value = kEmployeeId;
            obj.FromDataContract(svcEmployee.Read(new EmployeeKey{EmployeeId = kEmployeeId}));
            obj.PayHistoryObjectList.FromDataContract(svcEmployee.PayHistory_ReadList(new EmployeeKey{EmployeeId = kEmployeeId}));
            cfEmployee.Close();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            obj.Validate(true);
            ErrorList valErr = obj.GetValidationErrors();
            if (valErr.HasErrors())
            {
                Errors.Show(valErr);
                return;
            }

            ChannelFactory<IEmployeeService> cfEmployee = new ChannelFactory<IEmployeeService>("IEmployeeService");
            IEmployeeService svcEmployee = cfEmployee.CreateChannel();
            Employee_UpdateInput inUpdate = new Employee_UpdateInput();
            obj.ToDataContract(inUpdate);
            svcEmployee.Update(inUpdate);

            svcEmployee.SaveChanges(true);
            cfEmployee.Close();
            obj.SetModified(false, true);
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
